<script lang="ts" setup>
import { addFlashPromotion, updateFlashPromotion, getFlashPromotionDetail } from '@/api/flashPromotion';
import { useRoute } from 'vue-router';
import router from '@/router';

const route = useRoute();
const formRef = ref(ElForm);

const stateData = reactive({
  formData: {
    title: '',
  } as any,
  rules: {
    title: [
      {
        required: true,
        message: '请输入1-6字标题',
        trigger: 'blur'
      }
    ],
  },
});
const { formData, rules } = toRefs(stateData);


const dialog = reactive<any>({
  visible: false,
});


async function handleSubmit() {
  await formRef.value.validate((valid: boolean, val: any) => {
    if (valid) {
      if (formData.value.id) {
        updateFlashPromotion(formData.value)
          .then(async (res: any) => {
            ElMessage.success('操作成功');
            goBack()
          })

      } else {
        addFlashPromotion(formData.value)
          .then(async (res: any) => {
            ElMessage.success('操作成功');
            goBack()
          })
      }
    }
  });
}

/**
 * 类型表单弹窗
 *
 */
function openDialog(row?: object) {
  dialog.visible = true;
  if (row) {
    dialog.title = '预览';
    Object.assign(formData, row);
  } else {
    //resetForm();
    dialog.title = '预览';
  }
}

function goBack() {
  router.go(-1)
}

function getDetail() {
  getFlashPromotionDetail({
    id: Number(route.query.id)
  }).then((res: any) => {
    Object.assign(formData.value, res.data)
  });
}

watch(() => formData.value.id, () => {
  // fileList.value = formData.value.uploadInfo
})

onMounted(async () => {
  if (route.query.id) {
    formData.value.id = route.query.id
    await getDetail();
  }
});

</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form class="form-class" ref="formRef" :model="formData" :rules="rules" label-width="120px" label-position="left"
        size="large">
        <el-form-item class="form-item" label="标题" prop="title">
          <el-input class="input-item" v-model.trim="formData.title" placeholder="请输入1-6字标题" maxlength="6" />
        </el-form-item>
        <div class="fixed-footer">
          <div class="form-bottom-inner">
            <el-button class="sub-btn" @click="goBack()">返回</el-button>
            <el-button class="sub-btn" type="primary" @click="handleSubmit">保持</el-button>
          </div>
        </div>
      </el-form>

    </div>
  </div>
</template>
 
<style lang="scss" scoped>
.form-box {
  .form-box-inner {
    display: flex;
    justify-content: center;


    .form-item {
      width: 400px;
      margin-left: 30px;
    }
  }


}
</style>
  